// SED指标系统草稿页面模块
// 提供草稿页面的重置功能

(function(SEDFramework) {
    'use strict';

    console.log('[SED草稿模块] 模块开始加载');

    // 日志工具函数
    function log(message, type = 'info') {
        const timestamp = new Date().toLocaleString('zh-CN');
        const logMessage = `[SED草稿模块 ${timestamp}] ${message}`;
        
        switch(type) {
            case 'error':
                console.error(logMessage);
                break;
            case 'warn':
                console.warn(logMessage);
                break;
            case 'success':
                console.log(`%c${logMessage}`, 'color: green; font-weight: bold;');
                break;
            default:
                console.log(`%c${logMessage}`, 'color: blue;');
        }
    }

    // 检查当前页面是否为目标页面
    function isTargetPage() {
        // 获取完整路径，包括hash部分
        const currentPath = window.location.pathname;
        const currentHash = window.location.hash;
        const fullPath = currentPath + currentHash;
        
        const isTarget = fullPath.includes('group/fundamentalAnalysis/indicatorDraft/draft');
        log(`检查页面路径: ${currentPath}, Hash: ${currentHash}, 完整路径: ${fullPath}, 是否为目标页面: ${isTarget}`);
        return isTarget;
    }

    // ===== SweetAlert2 CDN自动引入 =====
    function ensureSweetAlert2() {
        return new Promise((resolve) => {
            if (window.Swal) {
                resolve();
                return;
            }
            var script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/sweetalert2@11';
            script.onload = function() { 
                console.log('SweetAlert2已加载');
                resolve();
            };
            script.onerror = function() {
                console.log('SweetAlert2加载失败，使用原生弹窗');
                resolve();
            };
            document.head.appendChild(script);
        });
    }
    
    // 等待SweetAlert2加载完成
    ensureSweetAlert2();

    // 添加按钮样式
    function addButtonStyles() {
        const style = document.createElement('style');
        style.textContent = `
            .reset-draft-btn {
                background: #3742fa;
                color: white;
                border: none;
                padding: 8px 12px;
                border-radius: 4px;
                cursor: pointer;
                font-size: 12px;
                margin: 5px;
                transition: background-color 0.3s;
            }
            
            .reset-draft-btn:hover {
                background: #2f3542;
            }
            
            .reset-draft-btn:disabled {
                background: #747d8c;
                cursor: not-allowed;
            }
        `;
        document.head.appendChild(style);
        log('按钮样式已添加');
    }

    // 统一弹窗函数
    async function showSwal(title, text = '', icon = 'info') {
        await ensureSweetAlert2();
        return Swal.fire(title, text, icon);
    }

    // 修改callResetDraftAPI函数，接受自定义请求体
    async function callResetDraftAPI(requestBody = {}) {
        log('开始调用重置草稿API');
        log(`请求体数据: ${JSON.stringify(requestBody)}`);
        
        // 查找重置按钮
        const button = document.querySelector('.reset-draft-btn');
        if (button) {
            button.disabled = true;
            button.textContent = '重置中...';
            log('按钮状态已更新为加载中');
        }
        
        // 构建请求URL
        const currentUrl = window.location.href;
        const baseUrl = currentUrl.split('/group/')[0];
        
        // 根据baseUrl动态设置网关地址
        let gatewayUrl;
        if (baseUrl === 'https://sed-uat.bewg.net.cn') {
            gatewayUrl = 'https://sed-uat-gateway.bewg.net.cn';
        } else if (baseUrl === 'https://sed.bewg.net.cn') {
            gatewayUrl = 'https://sed-gateway.bewg.net.cn';
        } else {
            // 默认使用uat网关
            gatewayUrl = 'https://sed-uat-gateway.bewg.net.cn';
            log(`未知的baseUrl: ${baseUrl}，使用默认网关地址`, 'warn');
        }
        
        const resetUrl = `${gatewayUrl}/external-api/report/draft/resetMedicamentDraft`;
        
        log(`重置API地址: ${resetUrl}`);
        
        // 从localStorage获取token
        const token = localStorage.getItem('token') || '';
        log(`从localStorage获取的token: ${token ? '已设置' : '未设置'}`);
        
        // 发送请求
        GM_xmlhttpRequest({
            method: 'POST',
            url: resetUrl,
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                'Authorization': token ? `Bearer ${token}` : '',
                'token': token
            },
            data: JSON.stringify(requestBody),
            onload: async function(response) {
                log(`API响应状态: ${response.status}`);
                log(`API响应内容: ${response.responseText}`);
                
                if (button) {
                    button.disabled = false;
                    button.textContent = '重置草稿';
                    log('按钮状态已恢复');
                }
                
                // 确保SweetAlert2已加载
                await ensureSweetAlert2();
                
                if (response.status === 200) {
                    try {
                        const result = JSON.parse(response.responseText);
                        log(`重置成功: ${JSON.stringify(result)}`, 'success');
                        await Swal.fire('草稿重置成功！', '', 'success');
                        
                        // 刷新页面
                        setTimeout(() => {
                            window.location.reload();
                        }, 1000);
                    } catch (e) {
                        log(`响应解析失败: ${e.message}`, 'error');
                        await Swal.fire('响应解析失败', e.message, 'error');
                    }
                } else {
                    log(`请求失败，状态码: ${response.status}`, 'error');
                    await Swal.fire('请求失败', '状态码：' + response.status, 'error');
                }
            },
            onerror: async function(error) {
                log(`网络请求失败: ${error.message}`, 'error');
                
                if (button) {
                    button.disabled = false;
                    button.textContent = '重置草稿';
                    log('按钮状态已恢复');
                }
                
                // 确保SweetAlert2已加载
                await ensureSweetAlert2();
                
                await Swal.fire('网络请求失败', error.message, 'error');
            }
        });
    }

    // 验证JSON格式的函数
    function validateJSON(jsonString) {
        try {
            JSON.parse(jsonString);
            return { isValid: true, data: null };
        } catch (error) {
            return { isValid: false, error: error.message };
        }
    }

    // 添加重置按钮
    function addResetButton() {
        log('开始查找目标容器 .card_right');
        
        // 查找目标容器
        const targetContainer = document.querySelector('.card_right');
        
        if (targetContainer) {
            log('找到目标容器，检查是否已存在按钮');
            
            // 检查是否已经添加过按钮
            if (targetContainer.querySelector('.reset-draft-btn')) {
                log('按钮已存在，跳过添加');
                return;
            }

            log('开始创建重置按钮');
            
            // 创建重置按钮
            const resetButton = document.createElement('button');
            resetButton.className = 'reset-draft-btn';
            resetButton.textContent = '重置草稿';
            resetButton.title = '点击重置当前草稿数据';
            
            // 添加点击事件
            resetButton.addEventListener('click', async function(e) {
                e.preventDefault();
                e.stopPropagation();
                log('重置按钮被点击');
                
                // 确保SweetAlert2已加载
                await ensureSweetAlert2();
                
                // 从本地存储中获取factoryNo、subFactoryNo和monthStr
                const factoryNo = localStorage.getItem('global_var_sed_factoryNo') || '';
                const subFactoryNo = localStorage.getItem('global_var_sed_subFactoryNo') || '';
                const monthStr = localStorage.getItem('global_var_sed_month') || '';
                const token = localStorage.getItem('token') || '';
                log(token);
                // 拼接成JSON对象
                const storageData = {
                    factoryNo: factoryNo,
                    monthStr: monthStr,
                    subFactoryNo: subFactoryNo
                };
                const jsonString = JSON.stringify(storageData, null, 2);
                
                log(`生成的JSON数据: ${jsonString}`);
                
                // 用SweetAlert2替换confirm，并显示可编辑的本地存储数据
                const result = await Swal.fire({
                    title: '确定要重置草稿吗？',
                    html: `
                        <div style="text-align: left; margin-bottom: 15px;">
                            <p style="margin-bottom: 10px;"><strong>此操作不可撤销。</strong></p>
                            <p style="margin-bottom: 5px;"><strong>factoryNo:</strong> ${factoryNo || '未设置'}</p>
                            <p style="margin-bottom: 5px;"><strong>monthStr:</strong> ${monthStr || '未设置'}</p>
                            <p style="margin-bottom: 15px;"><strong>subFactoryNo:</strong> ${subFactoryNo || '未设置'}</p>
                            <div style="text-align: left;">
                                <label style="display: block; margin-bottom: 5px; font-weight: bold;">编辑JSON数据 (将作为请求体发送):</label>
                                <textarea id="jsonData" style="width: 100%; height: 100px; padding: 8px; border: 1px solid #ddd; border-radius: 4px; font-family: monospace; font-size: 11px; resize: vertical;">${jsonString}</textarea>
                                <div id="jsonError" style="color: #e74c3c; font-size: 12px; margin-top: 5px; display: none;"></div>
                            </div>
                        </div>
                    `,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: '确定重置',
                    cancelButtonText: '取消',
                    width: '500px',
                    customClass: {
                        popup: 'reset-confirm-popup'
                    },
                    didOpen: () => {
                        // 添加JSON验证功能
                        const textarea = document.getElementById('jsonData');
                        const errorDiv = document.getElementById('jsonError');
                        const confirmBtn = Swal.getConfirmButton();
                        
                        if (textarea) {
                            // 实时验证JSON格式
                            textarea.addEventListener('input', () => {
                                const validation = validateJSON(textarea.value);
                                if (validation.isValid) {
                                    errorDiv.style.display = 'none';
                                    confirmBtn.disabled = false;
                                    confirmBtn.style.opacity = '1';
                                } else {
                                    errorDiv.textContent = `JSON格式错误: ${validation.error}`;
                                    errorDiv.style.display = 'block';
                                    confirmBtn.disabled = true;
                                    confirmBtn.style.opacity = '0.5';
                                }
                            });
                            
                            // 添加格式化功能（双击格式化）
                            textarea.addEventListener('dblclick', () => {
                                const validation = validateJSON(textarea.value);
                                if (validation.isValid) {
                                    const data = JSON.parse(textarea.value);
                                    textarea.value = JSON.stringify(data, null, 2);
                                    Swal.showValidationMessage('JSON已格式化！');
                                    setTimeout(() => Swal.closeValidationMessage(), 1000);
                                }
                            });
                        }
                    },
                    preConfirm: () => {
                        // 在确认前验证JSON
                        const textarea = document.getElementById('jsonData');
                        if (textarea) {
                            const validation = validateJSON(textarea.value);
                            if (!validation.isValid) {
                                Swal.showValidationMessage(`JSON格式错误: ${validation.error}`);
                                return false;
                            }
                            return JSON.parse(textarea.value);
                        }
                        return false;
                    }
                });
                
                if (result.isConfirmed && result.value) {
                    log('用户确认重置操作，使用编辑后的JSON数据');
                    log(`发送的请求体: ${JSON.stringify(result.value)}`);
                    callResetDraftAPI(result.value);
                } else {
                    log('用户取消重置操作或JSON验证失败');
                }
            });

            // 将按钮添加到容器中
            targetContainer.appendChild(resetButton);
            log('按钮已成功添加到页面', 'success');
        } else {
            log('未找到目标容器 .card_right', 'warn');
        }
    }

    // 模块初始化函数
    function init() {
        log('草稿页面模块开始初始化');
        log(`当前域名: ${window.location.origin}`);
        log(`当前路径: ${window.location.pathname}`);
        log(`当前Hash: ${window.location.hash}`);
        log(`完整URL: ${window.location.href}`);
        
        // 添加按钮样式
        addButtonStyles();
        
        // 检查是否为目标页面
        if (isTargetPage()) {
            log('当前页面符合条件，开始执行主要逻辑');
            
            // 等待页面加载完成
            if (document.readyState === 'loading') {
                log('页面正在加载中，等待DOMContentLoaded事件');
                document.addEventListener('DOMContentLoaded', function() {
                    log('DOMContentLoaded事件触发，开始添加按钮');
                    addResetButton();
                });
            } else {
                log('页面已加载完成，直接添加按钮');
                addResetButton();
            }
            
            // 监听路由变化（适用于SPA应用）
            log('开始监听路由变化');
            
            // 监听hash变化
            window.addEventListener('hashchange', function() {
                log(`Hash变化检测到: ${window.location.hash}`);
                if (isTargetPage()) {
                    log('Hash变化后仍为目标页面，重新添加按钮');
                    addResetButton();
                } else {
                    log('Hash变化后不再是目标页面');
                }
            });
            
            // 监听popstate事件（适用于使用History API的SPA）
            window.addEventListener('popstate', function() {
                log(`Popstate事件触发: ${window.location.hash}`);
                if (isTargetPage()) {
                    log('Popstate后仍为目标页面，重新添加按钮');
                    addResetButton();
                } else {
                    log('Popstate后不再是目标页面');
                }
            });
            
            // 定期检查URL变化（备用方案）
            let lastUrl = window.location.href;
            setInterval(function() {
                const currentUrl = window.location.href;
                if (currentUrl !== lastUrl) {
                    log(`URL变化检测到: ${lastUrl} -> ${currentUrl}`);
                    lastUrl = currentUrl;
                    if (isTargetPage()) {
                        log('URL变化后仍为目标页面，重新添加按钮');
                        addResetButton();
                    } else {
                        log('URL变化后不再是目标页面');
                    }
                }
            }, 1000);
        } else {
            log('当前页面不符合条件，模块不会执行主要功能');
        }
        
        log('草稿页面模块初始化完成');
    }

    console.log('[SED草稿模块] 模块加载完成，返回模块对象');

    // 返回模块对象
    return {
        name: 'DraftPage',
        version: '1.0',
        description: '草稿页面模块 - 提供重置草稿功能',
        init: init,
        isTargetPage: isTargetPage,
        addResetButton: addResetButton
    };

})(window.SEDFramework); 